#include "application.h"

#include <QDesktopServices>
#include <QDir>

#include <QDebug>

#include <QJson/Parser>

#include "app_state_model.h"
#include "main_window.h"
#include "pack_metadata.h"
#include "texture_pack.h"

const char* kPossibleAppDataDirs[] = {"Roaming", "Local", "LocalLow"};

QDir getMinecraftDir() {
  QDir dir(QDesktopServices::storageLocation(QDesktopServices::DataLocation));
  dir.cdUp();
  // On Mac or Linux, this is probably the right directory, so look for .minecraft or minecraft
  // as a subfolder.
  if (dir.cd(".minecraft") || dir.cd("minecraft")) {
    return dir;
  } else {
    // Oh boy. This is Windows, isn't it? And you gave us the wrong AppData directory, didn't you?
    // Yes, that's right, don't try to deny it, I see that guilty look in your eyes. Okay, fine,
    // we'll go look at all the others too.
    dir.cdUp();
    for (int i = 0; i < sizeof(kPossibleAppDataDirs) / sizeof(*kPossibleAppDataDirs); ++i) {
      if (dir.cd(kPossibleAppDataDirs[i])) {
        if (dir.cd(".minecraft") || dir.cd("minecraft")) {
          return dir;
        }
        dir.cdUp();
      }
    }
    // I give up, we can't find it. :(
    qWarning() << "Can't find the Minecraft directory!";
    return QDir();
  }
}

Application::Application(int& argc, char** argv) : QApplication(argc, argv) {
  setApplicationName("PackMerge");
  setApplicationVersion("1.0.0");
  Q_ASSERT(QFileInfo("tiles.json").exists());
  PackMetadata* metadata = new PackMetadata("tiles.json", this);
  app_state_ = new AppStateModel(this);
  app_state_->setPackMetadata(metadata);

  QFileInfo minecraft_jar;
  QDir minecraft_bin_dir = getMinecraftDir();
  minecraft_bin_dir.cd("bin");
  minecraft_jar.setFile(minecraft_bin_dir, "minecraft.jar");
  app_state_->addTexturePack(new TexturePack("Default", minecraft_jar, NULL, metadata));

  MainWindow* w = new MainWindow(app_state_);
  w->show();
}
